package com.k2data.etl;

import vcommon.utils.TimeUtils;
import vcommon.utils.httpclient.HttpMethod;
import vcommon.utils.httpclient.HttpsUtil;
import vcommon.utils.httpclient.SimpleHttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jodd.io.FileUtil;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class BqSime {
    private String outDir = "";

    public static void main(String[] args) throws Exception {
        BqSime sime = new BqSime();

        if (args.length <= 0) {
            System.out.println("no args.");
            return;
        }

        System.out.println(args[0]);

        JSONObject conf = null;
        try {
            String jsonConf = FileUtil.readString(args[0]);
            conf = JSON.parseObject(jsonConf);

            sime.outDir = conf.getString("outDir");

            List<RequestConf> rcs = JSON.parseArray(JSON.toJSONString(conf.getJSONArray("requests")), RequestConf.class);

            HttpClient httpClient = HttpsUtil.getHttpClient();
            for (RequestConf rc : rcs) {
                System.out.println(rc.getUrl());
                request(httpClient, rc, sime.outDir);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void request(HttpClient httpClient, RequestConf rc, String outDir) {
        try {
            SimpleHttpResponse response = HttpsUtil.request(httpClient, rc.getUrl(), rc.getHeaders(), HttpMethod.valueOf(rc.getMethod()), JSON.toJSONString(rc.getBody()), null);
            saveResponseToFile(response, outDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void saveResponseToFile(SimpleHttpResponse response, String outDir) throws IOException {
        StringBuilder sb = new StringBuilder();

        sb.append(response.getStatusCode()).append("\n");
        sb.append(response.getReason()).append("\n");

        sb.append("\n").append("\n");

        for (Header header : response.getHeaders()) {
            sb.append(header.getName()).append("=").append(header.getValue()).append("\n");
        }

        sb.append("\n").append("\n");

        sb.append(response.getText()).append("\n");

        FileUtil.writeString(new File(outDir + "/" + TimeUtils.now()), sb.toString());
    }

}
